from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import AIModel, ChatSession, ChatMessage, AIPromptTemplate, APIUsageLog, UserPreference


@admin.register(AIModel)
class AIModelAdmin(admin.ModelAdmin):
    list_display = ['name', 'model_type', 'is_active', 'max_tokens', 'temperature', 'created_at']
    list_filter = ['model_type', 'is_active', 'created_at']
    search_fields = ['name', 'description']
    list_editable = ['is_active']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'model_type', 'is_active')
        }),
        ('API配置', {
            'fields': ('api_endpoint', 'api_key'),
            'classes': ('collapse',)
        }),
        ('参数配置', {
            'fields': ('max_tokens', 'temperature')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )


class ChatMessageInline(admin.TabularInline):
    model = ChatMessage
    extra = 0
    readonly_fields = ['timestamp', 'tokens_used']
    fields = ['role', 'content', 'tokens_used', 'timestamp']
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('session')


@admin.register(ChatSession)
class ChatSessionAdmin(admin.ModelAdmin):
    list_display = ['title', 'user', 'ai_model', 'message_count_display', 'is_active', 'created_at', 'updated_at']
    list_filter = ['ai_model', 'is_active', 'created_at', 'user']
    search_fields = ['title', 'session_id', 'user__username']
    list_editable = ['is_active']
    readonly_fields = ['session_id', 'created_at', 'updated_at', 'message_count_display']
    inlines = [ChatMessageInline]
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'user', 'ai_model', 'is_active')
        }),
        ('系统信息', {
            'fields': ('session_id', 'message_count_display', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def message_count_display(self, obj):
        count = obj.message_count
        if count > 0:
            url = reverse('admin:ai_app_chatmessage_changelist') + f'?session__id__exact={obj.id}'
            return format_html('<a href="{}">{} 条消息</a>', url, count)
        return '0 条消息'
    message_count_display.short_description = '消息数量'


@admin.register(ChatMessage)
class ChatMessageAdmin(admin.ModelAdmin):
    list_display = ['session_title', 'role', 'content_preview', 'tokens_used', 'timestamp']
    list_filter = ['role', 'session__ai_model', 'timestamp']
    search_fields = ['content', 'session__title']
    readonly_fields = ['timestamp']
    
    fieldsets = (
        ('消息信息', {
            'fields': ('session', 'role', 'content')
        }),
        ('统计信息', {
            'fields': ('tokens_used', 'timestamp')
        })
    )
    
    def session_title(self, obj):
        return obj.session.title
    session_title.short_description = '会话标题'
    
    def content_preview(self, obj):
        if len(obj.content) > 100:
            return obj.content[:100] + '...'
        return obj.content
    content_preview.short_description = '消息预览'


@admin.register(AIPromptTemplate)
class AIPromptTemplateAdmin(admin.ModelAdmin):
    list_display = ['name', 'is_default', 'created_at']
    list_filter = ['is_default', 'created_at']
    search_fields = ['name', 'description']
    list_editable = ['is_default']
    readonly_fields = ['created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'is_default')
        }),
        ('提示词内容', {
            'fields': ('system_prompt', 'user_prompt_template')
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        })
    )


@admin.register(APIUsageLog)
class APIUsageLogAdmin(admin.ModelAdmin):
    list_display = ['ai_model', 'user', 'status', 'tokens_used', 'response_time', 'created_at']
    list_filter = ['ai_model', 'status', 'created_at']
    search_fields = ['user__username', 'ai_model__name']
    readonly_fields = ['created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'ai_model', 'session', 'status')
        }),
        ('请求内容', {
            'fields': ('request_content',),
            'classes': ('collapse',)
        }),
        ('响应内容', {
            'fields': ('response_content',),
            'classes': ('collapse',)
        }),
        ('统计信息', {
            'fields': ('tokens_used', 'response_time', 'error_message', 'created_at')
        })
    )
    
    def has_add_permission(self, request):
        # 不允许手动添加日志
        return False


@admin.register(UserPreference)
class UserPreferenceAdmin(admin.ModelAdmin):
    list_display = ['user', 'preferred_ai_model', 'default_temperature', 'theme', 'auto_save_history']
    list_filter = ['preferred_ai_model', 'theme', 'auto_save_history']
    search_fields = ['user__username']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('用户信息', {
            'fields': ('user',)
        }),
        ('AI设置', {
            'fields': ('preferred_ai_model', 'default_temperature', 'default_max_tokens')
        }),
        ('界面设置', {
            'fields': ('theme', 'auto_save_history')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )


# 自定义Admin站点标题
admin.site.site_header = 'AI11管理系统'
admin.site.site_title = 'AI Admin'
admin.site.index_title = '欢迎使用AI管理系统'
